# -*- coding: utf-8 -*-
# @Time    : 2021/3/11 10:26
# @Author  : zcn
# @Software: PyCharm

from fastapi import APIRouter

from apps.allsubdb.proxies_control.models import PostProxy
from apps.core.global_model import InputPlatformModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo, FAILED, SUCCESS

# from apps.sql_app.database import proxys_sql_conn
from apps.crawler_platform.util.sqlhelper import SQLHelper

router = APIRouter(route_class=ContextIncludedRoute)


async def sql_select_as():
    # 在自检表内取代理列表
    sql = "select proxy from proxy_management where task_name = 'noname' ORDER BY update_time asc"
    rows = await SQLHelper.fetchall(sql)
    # from main import app
    # pool = app.state.pool
    # async with pool.acquire() as conn:
    #     async with conn.cursor() as cur:
    #         await cur.execute(sql)
    #         rows = await cur.fetchall()
    row_list = [row[0] for row in rows]
    return row_list


async def sql_update_noname(proxy):
    # 更新代理标识为了获得更新时间方便后期取用
    sql_as = "update proxy_management set counts = counts+1 where proxy = %s and task_name = 'noname'"
    await SQLHelper.execute_commit(sql_as, (proxy,))
    # from main import app
    # pool = app.state.pool
    # async with pool.acquire() as conn:
    #     async with conn.cursor() as cur:
    #         await cur.execute(sql_as, (proxy))
    #         await conn.commit()


async def sql_update(proxy, TKname, SPname):
    # 更新自检表 前一个更新次数方便控制, 后一个更新代理标识为了获得更新时间方便后期取用
    sql = "update proxy_management set counts = counts+1 where proxy = %s and task_name = %s and task_tag = %s"
    # sql_as = "update proxy_management set counts = counts+1 where proxy = '{}' and task_name = 'noname'".format(proxy)
    await SQLHelper.execute_commit(sql, (proxy, TKname, SPname))
    # from main import app
    # pool = app.state.pool
    # async with pool.acquire() as conn:
    #     async with conn.cursor() as cur:
    #         await cur.execute(sql, (proxy, TKname, SPname))
    #         await conn.commit()
    # await proxys_sql_conn.execute(query=sql_as)


# @router.post("/proxies_get/get_one")
# async def get_proxy(input: InputPlatformModel[PostProxy]):
#     from main import app
#     return_info = ReturnInfo()
#     task_name = input.data.task_name
#     task_tag = input.data.task_tag
#     proxies_list = await sql_select_as()
#     sql_check = "select counts from proxy_management where proxy = %s and task_name = %s and task_tag = %s"
#
#     sql_insert = "insert ignore into proxy_management(proxy, task_name, task_tag) Values(%s, %s, %s)"
#
#     for proxy in proxies_list:
#         await sql_update_noname(proxy)
#         pool = app.state.pool
#         async with pool.acquire() as conn:
#             async with conn.cursor() as cur:
#                 await cur.execute(sql_check, (proxy, task_name, task_tag))
#                 row_check = await cur.fetchone()
#                 await conn.commit()
#         if row_check is None:
#             async with pool.acquire() as conn:
#                 async with conn.cursor() as cur:
#                     await cur.execute(sql_insert, (proxy, task_name, task_tag))
#                     await conn.commit()
#             return_info.status = SUCCESS
#             return_info.msg_code = 200
#             return_info.msg = "代理获取成功"
#             return_info.data = proxy
#             return return_info.todict()
#         elif row_check[0] < 3:
#             await sql_update(proxy, task_name, task_tag)
#             return_info.status = SUCCESS
#             return_info.msg_code = 200
#             return_info.msg = "代理获取成功"
#             return_info.data = proxy
#             return return_info.todict()
#     return_info.status = FAILED
#     return_info.msg_code = 200
#     return_info.msg = "现在时间段所有代理使用已达到阈值"
#     return_info.data = ''
#     return return_info.todict()


@router.post("/proxies_get/get_one")
async def get_proxy(input: InputPlatformModel[PostProxy]):
    sql_check = "select counts from proxy_management where proxy = %s and task_name = %s and task_tag = %s"
    sql_insert = "insert ignore into proxy_management(proxy, task_name, task_tag) Values(%s, %s, %s)"
    from main import app
    pool = app.state.pool
    return_info = ReturnInfo()
    task_name = input.data.task_name
    task_tag = input.data.task_tag

    if hasattr(app.state, "proxy_list"):
        try:
            while True:
                proxy = app.state.proxy_list.pop()
                row_check = await SQLHelper.fetchone(sql_check, (proxy, task_name, task_tag))
                # async with pool.acquire() as conn:
                #     async with conn.cursor() as cur:
                #         await cur.execute(sql_check, (proxy, task_name, task_tag))
                #         row_check = await cur.fetchone()
                #         await conn.commit()
                if row_check is None:
                    await SQLHelper.execute_commit(sql_insert, (proxy, task_name, task_tag))
                    # async with pool.acquire() as conn:
                    #     async with conn.cursor() as cur:
                    #         await cur.execute(sql_insert, (proxy, task_name, task_tag))
                    #         await conn.commit()
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "代理获取成功"
                    return_info.data = proxy
                    return return_info.todict()
                elif row_check[0] < 3:
                    await sql_update(proxy, task_name, task_tag)
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "代理获取成功"
                    return_info.data = proxy
                    return return_info.todict()

        except IndexError:
            if not hasattr(app.state, "proxy_judge") or app.state.proxy_judge is not True:
                app.state.proxy_judge = True
                try:
                    list_temp = await sql_select_as()
                    app.state.proxy_list.extend(list_temp)
                except:
                    app.state.proxy_judge = False
                finally:
                    app.state.proxy_judge = False
    else:
        app.state.proxy_list = await sql_select_as()

    return_info.status = FAILED
    return_info.msg_code = 200
    return_info.msg = "正在处理全局列表中,请稍候重试"
    return_info.data = ""
    return return_info.todict()
